import React, { useRef, useContext } from "react";
import { v4 as uuid } from "uuid";
import eventBus from "../eventBus";
import { scrollToError } from "../utils";

const MetadataContext = React.createContext();

function MetadataProvider({ children, id, onChange, mode = "Design", validateWithTouch = true, initialFormState = {}, params = {}, urlPrefix = "", csrfToken = "", csrfParam = "" }) {
  const parentMetadataManager = useContext(MetadataContext);
  let metadataManagerRef = useRef({
    parent: parentMetadataManager,
    isDesign: mode === "Design", //编辑模式
    isDisplay: mode === "Display" || mode==="Print", // 详情显示模式 和 打印模式 
    mode,
    id,
    onChange: onChange,
    validateWithTouch,
    forceUpdate: {},
    data: initialFormState,
    params: params,
    urlPrefix: urlPrefix, //appcode
    csrfToken: csrfToken,
    csrfParam: csrfParam,
  });

  if (parentMetadataManager) {
    metadataManagerRef.current.root = parentMetadataManager.root;
  } else {
    metadataManagerRef.current.root = metadataManagerRef.current;
  }

  //清除错误信息
  metadataManagerRef.current.clearError = function (keys = []) {
    if (metadataManagerRef.current.root.property?.hasError) {
      Object.keys(metadataManagerRef.current.root.property.hasError || {}).forEach((key) => {
        keys.forEach((k) => {
          if (~key.indexOf(k)) {
            delete metadataManagerRef.current.root.property.hasError[key];
          }
        });
      });
      metadataManagerRef.current.root.forceUpdate = uuid();
    }
  };

  //提交时调用表单校验触发，如果无错误，返回false
  metadataManagerRef.current.getError = function () {
    let allErrorKeys = Object.keys(metadataManagerRef.current.root.property?.hasError || {});
    metadataManagerRef.current.root.forceUpdate = {};
    if (allErrorKeys.length > 0) {
      allErrorKeys.forEach((field) => {
        eventBus.publish(updateField + field);
      });
      //dom更新完毕后focus到第一个报错的表单元素
      setTimeout(() => {
        try {
          //滚动到错误元素的位置
          scrollToError({
            scrollItemClass: ".has-error",
            contentClass: ".main-content",
            offsetY: -94
          })
        } catch (error) {
          //交互效果，出错了不影响功能
          console.warn("focus失败");
        }
      }, 0);
      return metadataManagerRef.current.root.property.hasError[allErrorKeys[0]];
    }
    return false;
  };

  return <MetadataContext.Provider value={metadataManagerRef.current}>{children}</MetadataContext.Provider>;
}

function useForm() {
  const context = React.useContext(MetadataContext);
  if (context === undefined) {
    throw new Error("useForm must be used within a FormProvider");
  }
  return context;
}

//开发时切换模式专用
const toggleMode = "form.toggleMode";

/**
 * 表单字段更新事件
 * @return {string} 固定值："form.field.update."
 * */
const updateField = "form.field.update.";
/**
 * 表单字段reload事件，
 * 1、发送updateField+fieldCode更新tplData.form.form_data数据
 * 2、发送"field.blur"事件触发字段规则
 * */
const reloadField = "form.field.reload";
export { MetadataProvider as Form, useForm, MetadataContext };
export { toggleMode, updateField,reloadField };
